<script setup lang='ts'>
import { ref, reactive } from "vue"
import { storeToRefs } from "pinia"
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from "element-plus"
import { Search, Minus, Plus } from '@element-plus/icons-vue'
import { useEnumStore } from "@/store/enumeration"
import { systemMessageAddPost } from "@/api/serviceSystem"
import useInstance from '@/hooks/useInstance';

const { templateType } = storeToRefs(useEnumStore())
defineOptions({
    name: 'addListAd'
})
const emit = defineEmits(['reflash'])
const { global } = useInstance();

const dialogBasic = ref({
    title: "新建短信模板",
    visible: false,
    width: 700,
    height: 400,
    showFooter: true,
    marginTop: "10vh",
})


const supplyFormRef = ref<FormInstance>()
const addSupply = reactive<any>({
    templateType: null, //模版类型
    templateName: null, //模版名称
    content: null, //模版内容 
    extInfo: [
        {
            key: null,
            value: null
        }
    ],

})

const rules = reactive<FormRules>({

    templateType: [
        {
            required: true,
            trigger: 'blur',
            message: "请选择模版类型"
        }
    ],
    content: [
        {
            required: true,
            trigger: 'blur',
            message: "请输入模版内容"
        }
    ],
    templateName: [
        {
            required: true,
            trigger: 'blur',
            message: "请输入模版名称"
        }
    ],

})

const btnAdd = () => {
    addSupply.extInfo.push({
        key: null,
        value: null
    })
}
const removeDomain = (item: any) => {
    const index = addSupply.extInfo.indexOf(item)
    if (index !== -1) {
        addSupply.extInfo.splice(index, 1)
    }
}
//显示弹框
const show = (type: string, row?: any) => {
    global.$resetForm(supplyFormRef.value, addSupply)
    if (type === 'add') {
        dialogBasic.value.title = "新建短信模板"
        addSupply.extInfo = [
            {
                key: null,
                value: null
            }
        ]
    } else {
        dialogBasic.value.title = "编辑短信模板"
        global.$objCopy(addSupply, row)


        const arr = JSON.parse(row.extInfo)
        if (Object.keys(arr).length > 0) {
            addSupply.extInfo = []
            Object.keys(arr).forEach(item => {
                addSupply.extInfo.push({
                    key: item,
                    value: arr[item]
                })
            })
        } else {
            addSupply.extInfo = [
                {
                    key: null,
                    value: null
                }
            ]
        }

    }
    dialogBasic.value.visible = true
}
const onClose = () => {

    addSupply.templateType = null
    addSupply.templateName = null
    addSupply.content = null

    addSupply.extInfo = [
        {
            key: null,
            value: null
        }
    ]

    resetForm()
    dialogBasic.value.visible = false
}
const resetForm = () => {
    supplyFormRef.value?.resetFields()
}
const onConfirm = async () => {
    await supplyFormRef.value?.validate(async isOk => {
        if (isOk) {
            try {
                const arr: any = {}
                addSupply.extInfo && addSupply.extInfo.forEach((item: any) => {
                    if (item.key) {
                        arr[item.key] = item.value
                    }
                })
                const newArr = Object.keys(arr).length == 0 ? "{}" : JSON.stringify(arr)
                const res = await systemMessageAddPost({ ...addSupply, extInfo: newArr })
                if (res.code == 20000) {
                    ElMessage({
                        message: addSupply?.id ? "短信模板编辑成功" : "短信模板新增成功",
                        type: "success"
                    })
                    emit('reflash')
                    onClose()
                }
            } catch (error) {
                ElMessage({
                    message: addSupply?.id ? "短信模板编辑失败 请重试！" : "短信模板新增失败 请重试！",
                    type: "warning"
                })
            }
        }
    })
}


defineExpose({
    show
})
</script>

<template>
    <SysDialog :title="dialogBasic.title" :width="dialogBasic.width" :height="dialogBasic.height"
        :show-footer="dialogBasic.showFooter" :visible="dialogBasic.visible" :margin-top="dialogBasic.marginTop"
        @on-close="onClose" @on-confirm="onConfirm">
        <template v-slot:content>
            <el-form ref="supplyFormRef" :model="addSupply" :rules="rules" label-width="120px" class="demo-ruleForm"
                status-icon>
                <el-form-item label="模版名称" prop="templateName">
                    <NormalInput v-model:model-value="addSupply.templateName"></NormalInput>
                </el-form-item>
                <el-form-item label="模版内容" prop="content">
                    <NormalInput v-model:model-value="addSupply.content"></NormalInput>
                </el-form-item>
                <el-form-item label="模版类型" prop="supplierKey">
                    <BlackSelect v-model:select-value="addSupply.templateType" :options="templateType"></BlackSelect>
                </el-form-item>
                <el-form-item v-for="(domain, index) in addSupply.extInfo" :key="index" :label="'信息扩展' + (index + 1)">
                    <el-row style="width: 100%;margin-bottom: 5px;" justify="space-around">
                        <el-col :span="6">
                            <el-input v-model="domain.key" placeholder="请输入value" :autosize="{ minRows: 2, maxRows: 4 }"
                                type="textarea"></el-input>
                        </el-col>
                        <el-col :span="15">
                            <el-input v-model="domain.value" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                                placeholder="请输入value" clearable></el-input>
                        </el-col>
                        <el-col :span="2">
                            <el-button type="danger" style="margin-top: 12px" size="small" @click="removeDomain(domain)"
                                :icon="Minus" />
                        </el-col>
                    </el-row>
                </el-form-item>


                <el-form-item label="添加信息扩展">
                    <el-button type="primary" @click="btnAdd" :icon="Plus" style="width: 100%;" />
                </el-form-item>

            </el-form>
        </template>
    </SysDialog>
</template>

<style lang='scss' scoped>
.demo-ruleForm {
    max-height: 480px;
    overflow: auto;
}
</style>
